package com.loren.oauth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.loren.oauth.data.resp.MicroResponse;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@AllArgsConstructor
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {

		response.setStatus(HttpStatus.UNAUTHORIZED.value());

		response.setContentType("application/json;charset=utf-8");

		String message;

		if (authException.getCause() instanceof OAuth2Exception) {
			OAuth2Exception oAuth2Exception = (OAuth2Exception) authException.getCause();
			message = oAuth2Exception.getOAuth2ErrorCode() + ", unauthorized access";
		} else if (authException instanceof InsufficientAuthenticationException) {
			InsufficientAuthenticationException insufficientAuthenticationException = (InsufficientAuthenticationException) authException;
			message = insufficientAuthenticationException.getMessage() + ", unauthorized access";
		} else {
			message = "unauthorized access";
		}

		MicroResponse<?> microResponse = MicroResponse.failure(MicroResponse.NEED_AUTH_CODE, message);

		response.getWriter().write(this.objectMapper.writeValueAsString(microResponse));
	}
}
